cc.Class({
    extends: cc.Component,

    properties: {

        audioBg: {
            type: cc.AudioClip,
            default: []
        },

        playerLabel: {
            type: cc.Node,
            default: null
        },
        armyLabel: {
            type: cc.Node,
            default: null
        },
        maskLabel:{
            type: cc.Node,
            default: null
        },
        fightMsgLabel:{
            type: cc.Node,
            default: null
        },
        controllerLabel:{
            type: cc.Node,
            default: null
        },

        controllerFaceNode:{
            type: cc.Node,
            default: null
        },

        btnHand:{
            type: cc.Node,
            default: null
        },

        btnAuto:{
            type: cc.Node,
            default: null
        },

        btnFightQuit:{
            type: cc.Node,
            default: null
        },

        btnSpeed:{
            type: cc.Node,
            default: null
        },

        btnVideo:{
            type: cc.Node,
            default: null
        },
    },

    start () {

        _TIPS.setNode(this.node);
        _MGD.setParentNode(this.node);

        window._FIGHT = this;

        this.successFlag = false;//战斗是否胜利

        this.ystart = 220;
        this.ylen = 110;
        this.growTime = 0.1;//能量积攒单位事件
        this.isWaiting = false;//是否可下命令

        this.isAutoFight = window.gameData.isAutoFight;//是否自动战斗

        if(this.isAutoFight){
            this.btnHand.active = true;
            this.btnAuto.active = false;
        }

        this.funcType = null;//当前命令类型
        this.funcSkillorItem = null;//当前技能道具选择

        this.cmdBtnArr = ['攻击','技能','道具','调查','撤退'];

        this.playerNodeMap = {};//角色节点map

        this.actionQueueLianji = [];//连击系行动队列

        this.actionQueueFanji = [];//反击系行动队列

        this.actionQueueXiezhan = [];//协战系行动队列

        this.doactionPlayer = null;//当前命令执行角色

        this.initFighter();

        this.energyGrow();

        this.initController();

        if(window.gameData.isPlayAudio){
            this.playBgm('fight',this.audioBg);
        }

    },

    playBgm:function(bgmname,audioBgArr){
		
		for(var i=0;i<audioBgArr.length;i++){
			
			if(audioBgArr[i].name == bgmname){
				
				cc.audioEngine.play(audioBgArr[i], true, 1);
				
				break;
				
			}
			
		}
		
	},

    showFightNodeSelect:function(funcType,skillOrItem){

        this.funcType = funcType;
        this.funcSkillorItem = skillOrItem;

        if(this.funcType=='攻击'){

            this.maskLabel.active = true;
            this.playerLabel.zIndex = 0;
            this.maskLabel.zIndex = 1;
            this.armyLabel.zIndex = 2;

        }else if(this.funcType=='调查'){

            this.maskLabel.active = true;
            this.maskLabel.zIndex = 0;
            this.playerLabel.zIndex = 1;
            this.armyLabel.zIndex = 2;

        }else if(this.funcType=='技能'){

            var skillobj = _SKILL[this.funcSkillorItem];
            
            if(skillobj.target=="army"){

                this.maskLabel.active = true;
                this.playerLabel.zIndex = 0;
                this.maskLabel.zIndex = 1;
                this.armyLabel.zIndex = 2;

            }else{

                this.maskLabel.active = true;
                this.playerLabel.zIndex = 2;
                this.maskLabel.zIndex = 1;
                this.armyLabel.zIndex = 0;

            }

        }else if(this.funcType=='道具'){

            var skillobj = _FIGHTITEM[this.funcSkillorItem];
            
            if(skillobj.target=="army"){

                this.maskLabel.active = true;
                this.playerLabel.zIndex = 0;
                this.maskLabel.zIndex = 1;
                this.armyLabel.zIndex = 2;

            }else{

                this.maskLabel.active = true;
                this.playerLabel.zIndex = 2;
                this.maskLabel.zIndex = 1;
                this.armyLabel.zIndex = 0;

            }

        }

    },

    //战斗按钮响应事件
    fightBtnFunc:function(){

        if(!_FIGHT.isWaiting){
            return;
        }

        //console.log(this.funcName);

        if(this.funcName=='撤退'){

            _FIGHT.isWaiting=false;

            _FIGHT.controllerLabel.active =false;

            var actioncmd={
                player:_FIGHT.doactionPlayer,
                type:'run'
            }

            _FIGHT.realDoAction(actioncmd);

        }else if(this.funcName=='攻击'||this.funcName=='调查'){

            _FIGHT.showFightNodeSelect(this.funcName,null);

        }else if(this.funcName=='技能'){
            _SKILLSELECTMANAGER.showSelect(_FIGHT.node,_ROLEDATA.getSkillOfplayer(_FIGHT.doactionPlayer),'skill');
        }else if(this.funcName=='道具'){

            //选择前先对道具排序
            window.gameData.fightItem.sort((a,b)=>{
                var typea = a.type;
                var typeb = b.type;
                var confa = _FIGHTITEM[typea];
                var confb = _FIGHTITEM[typeb];

                if(confa&&confb){
                    if(confa.skilltype==confb.skilltype){
                        return 0;
                    }else if(_FIGHTITEMHELPER.canUseInFight(typeb)){
                        return 1;
                    }else {
                        return -1;
                    }
                }
                return 0;
            });
            _SKILLSELECTMANAGER.showSelect(_FIGHT.node,window.gameData.fightItem,'item');
        }

    },

    //注册战斗按钮事件
    initFightBtnController:function(){

        var btns = this.controllerLabel.getChildByName('commond').getChildByName('btns');
        for(var i=0;i<this.cmdBtnArr.length;i++){

            if(btns.getChildren()[i]){

                var btn = btns.getChildren()[i];
                btn.getChildByName('Background').
                    getChildByName('Label').
                    getComponent(cc.Label).string = this.cmdBtnArr[i];
                btn.funcName = this.cmdBtnArr[i];
                btn.on(cc.Node.EventType.TOUCH_START,this.fightBtnFunc,btn); 

            }

        }

    },

    resetCmd:function(){
        this.maskLabel.active =false;
        this.funcType = null;
        this.funcSkillorItem = null;

    },

    //注册所有按钮事件
    initController:function(){

        if(_QD.showVideoBtn()){
            this.btnVideo.getParent().active = true;
        }

        this.btnVideo.on(cc.Node.EventType.TOUCH_START, function(){
            
            console.log('录屏按钮...');

            VDM.startRecord();

        }, this); 

        this.btnFightQuit.on(cc.Node.EventType.TOUCH_START, function(){
            //console.log('投降');
            _CHOICEMANAGER.showChoice(this.node,'quitFight',null);
        }, this); 

        this.btnAuto.on(cc.Node.EventType.TOUCH_START, function(){

            //console.log('自动');

            this.btnHand.active = true;
            this.btnAuto.active = false;
            this.isAutoFight=true;

            if(this.isWaiting){
                this.isWaiting = false;
                this.aiAttackAfter();
            }

        }, this); 

        this.btnHand.on(cc.Node.EventType.TOUCH_START, function(){

            //console.log('手动');

            this.btnHand.active = false;
            this.btnAuto.active = true;
            this.isAutoFight=false;
        }, this); 

        this.btnSpeed.on(cc.Node.EventType.TOUCH_START,this.switchFightSpeed,this);

        this.maskLabel.on(cc.Node.EventType.TOUCH_START,this.resetCmd, this); 

        this.refreshFightSpeed();

        this.initFightBtnController();

    },

    giveBackAll:function(){
        _GRM.getBackNode(this.playerLabel);
        _GRM.getBackNode(this.armyLabel);
    },

    //激活判定
    ifActive:function(player,playerNode){

        var beActive = _ROLEDATA.getRealAttr(player,'beActive');
        if(beActive>=1){

            var animalSkill = this.randomAnimalsSkill(player);
            if(animalSkill){

                _FAM.doConceAnimals(animalSkill,player,playerNode);
                _MFN.refreshPlayerNode(playerNode,player);
            }

        }

    },

    randomAnimalsSkill:function(player){

        if(player&&player.skill){

            for(var i=0;i<player.skill.length;i++){
                var tmpskillname = player.skill[i];
                if(_SKILL[tmpskillname]&&_SKILL[tmpskillname].animals){
                    return _SKILL[tmpskillname];
                }else if(_SKILLBD[tmpskillname]&&_SKILLBD[tmpskillname].animals){
                    return _SKILLBD[tmpskillname];
                }

            }

        }

        return null;

    },

    tongling:function(){

        if(
            fightData
            &&fightData.playerTeam
            &&fightData.playerTeam.length<5
            &&window.gameData.catchMonster
            &&_NPC[window.gameData.catchMonster]
            &&_GAMEDATAHELPER.hasTeamSkill('tongling')
        ){

            var goodsIndex = _GAMEDATAHELPER.getUnlockGoodsIndex(window.gameData.fightItem,'唤妖符');

            if(
                goodsIndex!=-1
                &&_GAMEDATAHELPER.reduceGoods(window.gameData.fightItem,goodsIndex,1)
            ){

                var playerFtype = window.gameData.playerTeam[0].ftype;
                var playerLv = _EXPMANAGER.getLevelByExp(window.gameData.playerTeam[0].exp);
                var tempmonster = _ROF.createAnimal(window.gameData.catchMonster,playerLv,{ftype:playerFtype});
                tempmonster.isCustomRole = true;
                tempmonster.isZhaohuan = true;
                fightData.playerTeam.push(tempmonster);

            }
        }

    },

    //返回是否有威风
    initBeginStatus:function(role){

        var roleData = _ROLEDATA.getRoleDataOfPlayer(role);

        if(roleData.beginEnergy){
            role.eg = roleData.beginEnergy;
        }

        if(roleData.dun){
            _FAM.addPlayerStatusArr(['dang_1'],role);
        }

        if(roleData.shendun){
            _FAM.addPlayerStatusArr(['dun_1'],role);
        }

        return roleData.weifeng?true:false;
    },

    initFighter:function(){

        this.tongling();

        var armyweifeng = false;
        var playerwefeng = false;

        for(var i=0;i<fightData.playerTeam.length;i++){
            fightData.playerTeam[i].teamIndex = i;
            fightData.playerTeam[i].isplayer = true;
            fightData.playerTeam[i].animals = null;
            fightData.playerTeam[i].historyAnimals={};
            fightData.playerTeam[i].statusArr = [];
            fightData.playerTeam[i].eg = 0;

            /*
            fightData.playerTeam[i].eg = _ROLEDATA.getRealAttr(fightData.playerTeam[i],'beginEnergy');
			if(_ROLEDATA.getRealAttr(fightData.playerTeam[i],'dun')){
				_FAM.addPlayerStatusArr(['dang_1'],fightData.playerTeam[i]);
			}
            */

            if(this.initBeginStatus(fightData.playerTeam[i])){
                playerwefeng = true;
            }

            var fnode = _MFN.createPlayerNode(fightData.playerTeam[i],true);
            fnode.setPosition(cc.v2(0,this.ystart-i*this.ylen));
            this.playerLabel.addChild(fnode);
            this.playerNodeMap['player-'+i]=fnode;
            this.ifActive(fightData.playerTeam[i],fnode);
        }

        for(var i=0;i<fightData.armyTeam.length;i++){
            fightData.armyTeam[i].teamIndex = i;
            fightData.armyTeam[i].isplayer = false;
            fightData.armyTeam[i].animals = null;
            fightData.armyTeam[i].historyAnimals={};
            fightData.armyTeam[i].statusArr = [];
            _ROF.recreateObjByHdlv(fightData.armyTeam[i]);
            fightData.armyTeam[i].eg = 0;

            /*
            fightData.armyTeam[i].eg = _ROLEDATA.getRealAttr(fightData.armyTeam[i],'beginEnergy');
			if(_ROLEDATA.getRealAttr(fightData.armyTeam[i],'dun')){
				_FAM.addPlayerStatusArr(['dang_1'],fightData.armyTeam[i]);
			}
            */
            if(this.initBeginStatus(fightData.armyTeam[i])){
                armyweifeng = true;
            }

            var fnode = _MFN.createPlayerNode(fightData.armyTeam[i],false);
            fnode.setPosition(cc.v2(0,this.ystart-i*this.ylen));
            this.armyLabel.addChild(fnode);
            this.playerNodeMap['army-'+i]=fnode;
            this.ifActive(fightData.armyTeam[i],fnode);
        }

        if(armyweifeng){
            for(var i=0;i<fightData.playerTeam.length;i++){
                if(fightData.playerTeam[i].eg>0){
                    fightData.playerTeam[i].eg = 0;
                    _MFN.refreshPlayerInfo(this.playerNodeMap['player-'+i],fightData.playerTeam[i]);
                }
            }
        }

        if(playerwefeng){
            for(var i=0;i<fightData.armyTeam.length;i++){
                if(fightData.armyTeam[i].eg>0){
                    fightData.armyTeam[i].eg = 0;
                    _MFN.refreshPlayerInfo(this.playerNodeMap['army-'+i],fightData.armyTeam[i]);
                }
            }
        }

    },

    //判断衍生动作是否可执行
    checkCmdEnable:function(actionCmd){

        if(
            actionCmd
            &&actionCmd.player
            //&&actionCmd.player.hp>0
            &&this.checkPlayerCanDoAction(actionCmd.player)
        ){

            if(actionCmd.targetArr){
                var targetArr = actionCmd.targetArr;
                var enable = false;
                for(var i=0;i<targetArr.length;i++){
                    if(targetArr[i].hp>0){
                        enable= true;
                    }
                }
                return enable;
            }else if(actionCmd.target){
                if(actionCmd.target.hp<=0){
                    return false;
                }
            }
            

            return true;

        }

        return false;

    },

    //判断衍生动作
    checkYSAction:function(){

        

        for(var i=0;i<this.actionQueueLianji.length;){
            var actionCmd = this.actionQueueLianji[i];
            this.actionQueueLianji.splice(i,1);
            if(this.checkCmdEnable(actionCmd)){
                this.node.runAction(cc.sequence(_FAM.getActionArr(actionCmd)));
                return true;
            }
        }

        for(var i=0;i<this.actionQueueFanji.length;){
            var actionCmd = this.actionQueueFanji[i];
            this.actionQueueFanji.splice(i,1);
            if(this.checkCmdEnable(actionCmd)){
                this.node.runAction(cc.sequence(_FAM.getActionArr(actionCmd)));
                return true;
            }
        }

        for(var i=0;i<this.actionQueueXiezhan.length;){
            var actionCmd = this.actionQueueXiezhan[i];
            this.actionQueueXiezhan.splice(i,1);
            if(this.checkCmdEnable(actionCmd)){
                this.node.runAction(cc.sequence(_FAM.getActionArr(actionCmd)));
                return true;
            }
        }

        return false;

    },

    runSuccess:function(){
        this.giveBackAll();
        window._JUMPSENCE = 'map';
        cc.director.loadScene('jump');
    },

    //能力增长
    energyGrow:function(){

        //console.log('step1boss状态',window.fightData.armyTeam[0].statusArr);

        if(this.isFightOver()){
            this.giveBackAll();
            if(this.successFlag){
                window._JUMPSENCE = 'success';
            }else{
                window._JUMPSENCE = 'faile';
            }
            console.log('战斗结束 跳转:'+window._JUMPSENCE);
            cc.director.loadScene('jump');
            return;
        }

        if(this.checkYSAction()){
            return ;
        }

        //console.log('step2boss状态',window.fightData.armyTeam[0].statusArr);

        if(!this.getDoActionPlayer()){

            for(var i=0;i<fightData.playerTeam.length;i++){
                var player = fightData.playerTeam[i];
                if(player.hp>0){
                    //player.eg+=player.sd;
                    player.eg+=_ROLEDATA.getRealAttr(player,'speed');
                }
                _MFN.refreshPlayerInfo(this.playerNodeMap['player-'+i],player);
            }

            for(var i=0;i<fightData.armyTeam.length;i++){
                var player = fightData.armyTeam[i];
                if(player.hp>0){
                    //player.eg+=player.sd;
                    player.eg+=_ROLEDATA.getRealAttr(player,'speed');
                }
                _MFN.refreshPlayerInfo(this.playerNodeMap['army-'+i],player);
            }

            //console.log('step3boss状态',window.fightData.armyTeam[0].statusArr);

            this.node.runAction(
                cc.sequence(
                    cc.delayTime(this.growTime),
                    cc.callFunc(this.energyGrow,this)
                )
            );

        }else{

            this.doAction();

        }

    },

    getDoActionPlayer:function(){

        this.doactionPlayer = null;
        var faststEg = _CS.maxEnergy;

        for(var i=0;i<fightData.playerTeam.length;i++){

            if(fightData.playerTeam[i].hp>0&&fightData.playerTeam[i].eg>=faststEg){
                this.doactionPlayer = fightData.playerTeam[i];
                faststEg=fightData.playerTeam[i].eg;
            }

        }

        for(var i=0;i<fightData.armyTeam.length;i++){

            if(fightData.armyTeam[i].hp>0&&fightData.armyTeam[i].eg>=faststEg){
                this.doactionPlayer = fightData.armyTeam[i];
                faststEg=fightData.armyTeam[i].eg;
            }

        }

        if(this.doactionPlayer){

            this.doactionPlayer.eg = this.doactionPlayer.eg-_CS.maxEnergy;

            this.fightLog(this.doactionPlayer.name+"开始行动了...");

            //console.log('当前行动人:',this.doactionPlayer);

            return true;

        }else{

            //console.log('当前无行动人:',this.doactionPlayer);

            return false;

        }

    },

    getRandomActionTarget:function(){

        var tmparr = [];
        var sourcearr = this.doactionPlayer.isplayer?window.fightData.armyTeam:window.fightData.playerTeam;
        
        for(var i=0;i<sourcearr.length;i++){
            if(sourcearr[i].hp>0){
                tmparr.push(sourcearr[i]);
            }
        }

        if(tmparr.length>0){
            return _CU.randomObj(tmparr);
        }

        return null;

    },


    doAction:function(){
        
        if(!this.doactionPlayer.isplayer||this.doactionPlayer.isCustomRole){

            this.aiAttack();

        }else{

            if(!this.isAutoFight){
                var actioncmd={
                    player:this.doactionPlayer,
                    type:'wait'
                }
                this.realDoActionWithBefore(actioncmd);
            }else{

                this.aiAttack();
            }
        }
    },

    aiAttackAfter:function(){

        var actioncmd = _FIGHTAI.getActionCmd(this.doactionPlayer);

        this.realDoAction(actioncmd);
    },

    aiAttack:function(){

        var actioncmd = _FIGHTAI.getActionCmd(this.doactionPlayer);

        this.realDoActionWithBefore(actioncmd);
    },

    realDoAction:function(actioncmd){

        this.node.runAction(cc.sequence(_FAM.getActionArr(actioncmd)));

    },

    realDoActionWithBefore:function(actioncmd){
        var beforaction = _FAM.getActionArrBeforeRealAction(actioncmd);
        if(beforaction.length<=0){
            this.node.runAction(cc.sequence(_FAM.getActionArr(actioncmd)));
        }else{
            this.node.runAction(cc.sequence(beforaction.concat(_FAM.getActionArr(actioncmd))));
        }
    },

    //等待指令
    waitCmd:function(){

        this.fightMsgLabel.active = false;
        this.controllerLabel.active = true;
        if(this.doactionPlayer){
            this.controllerFaceNode.getComponent(cc.Sprite).spriteFrame = _GRM.getFaceFrame(this.doactionPlayer.face);
        }
        this.isWaiting = true;

    },

    isFightOver:function(){

        //console.log('检测战斗是否结束',window.fightData.playerTeam,window.fightData.armyTeam);

        var isover = true;
        for(var i=0;i<window.fightData.playerTeam.length;i++){
            if(window.fightData.playerTeam[i].hp>0){
                isover = false;
                break;
            }
        }

        if(isover){
            this.successFlag = false;
            return isover;
        }

        isover = true;
        for(var i=0;i<window.fightData.armyTeam.length;i++){
            if(window.fightData.armyTeam[i].hp>0){
                isover = false;
                break;
            }
        }

        this.successFlag = true;
        return isover;
    },

    //根据角色信息获取角色节点
    getPlayerNodeByPlayer:function(player){
        if(player){
                return player.isplayer?
                this.playerNodeMap["player-"+player.teamIndex]
                :this.playerNodeMap["army-"+player.teamIndex];
        }else{
            return null;
        }
    },

    //根据角色信息获取角色队友
    getteamPlayerArrByPlayer:function(player,isAlive){

        if(player){

            var source = player.isplayer?window.fightData.playerTeam:window.fightData.armyTeam;
            var playerIndex = player.teamIndex;
            var arr = [];

            for(var i=0;i<source.length;i++){
                if(source[i].teamIndex!=playerIndex){
                    if(isAlive){
                        if(source[i].hp>0){
                            arr.push(source[i]);
                        }
                    }else{
                        if(source[i].hp<=0){
                            arr.push(source[i]);
                        }
                    }
                }
            }

            return arr;

        }


        return null;

    },

    //取player同阵营或者相反阵营的队伍  isArmy true--相反阵营  false--同阵营
    getArmyTeamByPlayer:function(player,isArmy){

        if(player){
            var source = (!isArmy)?
                        (player.isplayer?window.fightData.playerTeam:window.fightData.armyTeam)
                        :(player.isplayer?window.fightData.armyTeam:window.fightData.playerTeam);
            var playerIndex = player.teamIndex;
            var arr = [];
            for(var i=0;i<source.length;i++){
                if(source[i].hp>0){
                    arr.push(source[i]);
                }
            }
            return arr;
        }
        return null;
    },

    getArmyTeamByPlayerForLive:function(player,isArmy){

        if(player){
            var source = (!isArmy)?
                        (player.isplayer?window.fightData.playerTeam:window.fightData.armyTeam)
                        :(player.isplayer?window.fightData.armyTeam:window.fightData.playerTeam);
            var playerIndex = player.teamIndex;
            var arr = [];
            for(var i=0;i<source.length;i++){
                arr.push(source[i]);
            }
            return arr;
        }
        return null;
    },


    refreshFightSpeed:function(){

        if(window.gameData&&window.gameData.fightSpeed){
            this.btnSpeed.getChildByName('Background')
                        .getChildByName('Label')
                        .getComponent(cc.Label).string = "加速("+window.gameData.fightSpeed+")";
            cc.director.getScheduler().setTimeScale(window.gameData.fightSpeed);
        }
    },

    switchFightSpeed:function(){

        if(window.gameData&&window.gameData.fightSpeed){

            if(window.gameData.fightSpeed<3){
                window.gameData.fightSpeed++;
            }else{
                window.gameData.fightSpeed=1;
            }

            this.refreshFightSpeed();

        }   

        
    },

    fightLog:function(msg){
        this.controllerLabel.active = false;
        this.fightMsgLabel.active =true;
        this.fightMsgLabel.getChildByName('commond')
                        .getChildByName('message')
                        .getComponent(cc.Label).string = msg;
    },

    fightLogAdd:function(msg){
        this.controllerLabel.active = false;
        this.fightMsgLabel.active =true;
        var cclabel = this.fightMsgLabel.getChildByName('commond')
        .getChildByName('message')
        .getComponent(cc.Label);

        if(cclabel.string)
            cclabel.string += "\n"+msg;
        else
            cclabel.string=msg;
    },

    checkPlayerCanDoAction:function(player){

       

        return player.hp>0
               &&
               !RSH.hasHun(player.statusArr);
               /*
               (
                !player.statusArr
               ||!RSH.hasHun(player.statusArr)
               );
               */

    },

    getCfByplayer:function(player){

        if(RSH.hasdang(player.statusArr)){
            return player;
        }else{

            var team = this.getteamPlayerArrByPlayer(player,true);

            for(var i=0;i<team.length;i++){
                if(RSH.hasdang(team[i].statusArr)){
                    return team[i];
                }
            }

        }

        return player;

    },

    // update (dt) {},
});
